<template>
  <div class="app-container">

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="我的余额" style="margin-left: 30px">
        <div style="color: green; font-size: 20px">{{ balancePrice }}元</div>
      </el-form-item>
      <el-form-item label="交易单号" prop="number" style="margin-left: 50px">
        <el-input
          v-model="queryParams.number"
          placeholder="请输入交易单号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="变动类型" prop="changeType" style="margin-left: 50px">
        <el-select v-model="queryParams.changeType" size="small" style="width: 190px; margin-right: 10px">
          <el-option v-for="item in changeTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="商户名称" prop="merchantId" style="margin-left: 50px" v-if="isOne">
        <template #default="scope">
          <el-select filterable clearable v-model="queryParams.merchantName" size="small" style="width: 200px; margin-right: 10px" @change="merchantChange(queryParams.merchantName)">
            <el-option v-for="item in merchantArr" :key="item.account" :label="item.account" :value="item.account" />
          </el-select>
        </template>
      </el-form-item>

      <el-form-item label="变动时间" style="width: 308px">
        <el-date-picker
            v-model="queryParams.searchDateRange"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
      </el-form-item>
    </el-form>

<!--
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['business:merchantCapital:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
-->

    <el-table v-loading="loading" :data="merchantCapitalList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />

      <el-table-column label="图片" align="center" prop="img" width="150px" fixed class="el-image-viewer_wrapper">
        <template #default="scope">
          <el-image v-if="scope.row.img !== null"
              style="width: 100px; height: 100px"
              :key="scope.row.id"
              :src="scope.row.img"
              :preview-teleported="true"
              :preview-src-list="[scope.row.img]">
          </el-image>

          <span v-if="scope.row.img === null"></span>
        </template>
      </el-table-column>

      <el-table-column label="商户名称" align="center" prop="merchantName" min-width="100"/>

      <el-table-column label="变动类型" align="center" prop="changeType">
        <template #default="scope">
          <span v-if="scope.row.changeType === 'in'">客户充值</span>
          <span v-if="scope.row.changeType === 'out'">订单支付</span>
          <span v-if="scope.row.changeType === 'freightOut'">运费支付</span>
          <span v-if="scope.row.changeType === 'backIn'">订单退回</span>
        </template>
      </el-table-column>

      <el-table-column label="交易单号" align="center" prop="number" min-width="150">
        <template #default="scope">
          <el-button link type="primary" @click="openOrderDetail(scope.row.orderId)" v-if="scope.row.changeType === 'out' || scope.row.changeType === 'freightOut' || scope.row.changeType === 'backIn'">
            {{ scope.row.number }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="变动前的金额" align="center" prop="beforeChangeAmount" />

      <el-table-column label="变动的金额" align="center" prop="changeAmount">
        <template #default="scope">
          <span style="color: green;" v-if="scope.row.changeType === 'in'">+ {{scope.row.changeAmount }}</span>
          <span style="color: red;" v-if="scope.row.changeType === 'out'">- {{scope.row.changeAmount }}</span>
          <span style="color: red;" v-if="scope.row.changeType === 'freightOut'">- {{scope.row.changeAmount }}</span>
          <span style="color: green;" v-if="scope.row.changeType === 'backIn'">+ {{scope.row.changeAmount }}</span>
        </template>
      </el-table-column>


      <el-table-column label="变动后的金额" align="center" prop="afterChangeAmount" />
      <el-table-column label="变动时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="备注" align="center" prop="remark" />
<!--      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
<!--        <template #default="scope">-->
<!--          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['business:merchantCapital:edit']">修改</el-button>-->
<!--          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['business:merchantCapital:remove']">删除</el-button>-->
<!--        </template>-->
<!--      </el-table-column>-->
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商户的资金流水对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="merchantCapitalRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="交易单号" prop="number">
          <el-input v-model="form.number" placeholder="请输入交易单号" />
        </el-form-item>
        <el-form-item label="变动的金额" prop="changeAmount">
          <el-input v-model="form.changeAmount" placeholder="请输入变动的金额" />
        </el-form-item>
        <el-form-item label="变动前的金额" prop="beforeChangeAmount">
          <el-input v-model="form.beforeChangeAmount" placeholder="请输入变动前的金额" />
        </el-form-item>
        <el-form-item label="变动后的金额" prop="afterChangeAmount">
          <el-input v-model="form.afterChangeAmount" placeholder="请输入变动后的金额" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- Detail 组件 -->
    <Detail ref="detailRef" />
  </div>
</template>

<script setup name="MerchantCapital">
import { listMerchantCapital, getMerchantCapital, delMerchantCapital, addMerchantCapital, updateMerchantCapital, getMyMerchantBalance } from "@/api/business/merchantCapital";
import {getMyMerchantInvoice} from "../../../api/business/merchantInvoice";
import { allListMerchantInfo } from "@/api/business/merchant";
import { getIsAdmin } from "@/api/system/user";
import { getIsManage } from "@/api/system/user";
import Detail from './orderDetail.vue';

const { proxy } = getCurrentInstance();

const merchantCapitalList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const balancePrice = ref(0);
const isOne = ref(true);//是单条还是多条
const merchantArr = ref([]);//商户list
const detailRef = ref(null);//详情弹窗
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    number: null,
    merchantName: null,
    merchantId: null,
    searchDateRange:null,
    changeType: null,
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

const changeTypeOptions = ref([
  {
    value: '',
    label: '全部'
  },{
    value: 'in',
    label: '客户充值'
  },{
    value: 'out',
    label: '订单支付'
  }, {
    value: 'backIn',
    label: '订单退回'
  }
]);

/** 查询商户的资金流水列表 */
function getList() {
  loading.value = true;
  listMerchantCapital(queryParams.value).then(response => {
    merchantCapitalList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function getMyMerchantInfo() {

  getMyMerchantBalance().then(response => {

    console.log("-----response------" + response)
    console.log("-----response.rows------" + response.data)
    balancePrice.value = response.data;

  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    number: null,
    changeAmount: null,
    beforeChangeAmount: null,
    afterChangeAmount: null,
    changeType: null,
    remark: null,
    createTime: null
  };
  proxy.resetForm("merchantCapitalRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
  getMyMerchantInfo();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加资金流水";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getMerchantCapital(_id).then(response => {
    form.value = response.data;
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["merchantCapitalRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateMerchantCapital(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addMerchantCapital(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除资金流水？').then(function() {
    return delMerchantCapital(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('business/merchantCapital/export', {
    ...queryParams.value
  }, `资金流水_${new Date().getTime()}.xlsx`)
}


/** 查询商户信息列表 */
function getMerchantList() {
  allListMerchantInfo().then(response => {
    merchantArr.value = response.rows;
  });
}

function merchantChange(name){
  for (let i = 0; i < merchantArr.value.length; i++) {
    if (merchantArr.value[i].account === name) {
      queryParams.value.merchantName = name;
      queryParams.value.merchantId = merchantArr.value[i].id;
    }
  }
}

/** 获取是单条还是多条 */
function getUserRole() {
  // getIsAdmin().then(response => {
  getIsManage().then(response => {
    console.log("---------" , response)
    isOne.value = response;
  });
}

// 详情
function openOrderDetail(id) {
  if (detailRef.value) detailRef.value.init(id);
}


getList();
getMyMerchantInfo();
getMerchantList();// 获取所有商户
getUserRole();
</script>

<style scoped>
.el-image-viewer_wrapper{
  z-index: 20028 !important;
}
</style>

<style scoped>
.el-image-viewer_wrapper{
  z-index: 20028 !important;
}
</style>

<style scoped>
.el-image-viewer_wrapper{
  z-index: 20028 !important;
}
</style>